/*
 * @Author: wujiedong
 * @Date: 2021-03-15 09:17:40
 * @LastEditors: wujiedong
 * @LastEditTime: 2022-04-25 17:23:14
 * @FilePath: \vue-blog-web\vue.config.js
 * @Description:
 */
const path = require('path')

module.exports = {
  devServer: {
    port: 9528
  },
  configureWebpack: {
    devtool: 'source-map'
  },
  chainWebpack: config => {
    // 配置目录别名
    config.resolve.alias
    .set('@styles', path.resolve(__dirname, 'src/assets/styles'))
    .set('@images', path.resolve(__dirname, 'src/assets/images'))
    .set('@pages', path.resolve(__dirname, 'src/pages'))
    .set('@request', path.resolve(__dirname, 'src/request'))
    .set('@components', path.resolve(__dirname, 'src/components'))
    .set('@utils', path.resolve(__dirname, 'src/utils'))
    .set('@plugins', path.resolve(__dirname, 'src/plugins'))

    const env = process.env.NODE_ENV
    config.when(env === 'production', config => { // 部署环境
      config.devtool('cheap-module-source-map')
      // 去掉console代码
      config.optimization
        .minimizer('terser')
        .tap(args => {
          args[0].terserOptions.compress.drop_console = true
          return args
        })
      // 代码打包生成gz压缩文件
      const compressionPlugin = require('compression-webpack-plugin')
      config
        .plugin('compression')
        .use(compressionPlugin, [{
          test: /\.js$|\.css$|\.html$/,
          threshold: 10240 // 大于10KB的文件才会被压缩
        }])
      // 打包之后直接形成zip文件 https://www.npmjs.com/package/filemanager-webpack-plugin
      const filemanagerPlugin = require('filemanager-webpack-plugin')
      config
        .plugin('filemanager')
        .use(filemanagerPlugin, [{
          events: {
            onEnd: {
              archive: [
                { source: './dist', destination: './dist.zip' }
              ]
            }
          }
        }])
      initCdn(config) // 设置cdn
    },
    config => { // 开发环境
      config.devtool('source-map')
    })
  }
}

// 设置cdn,降低打包之后vendor文件体积
function initCdn(config) {
  const externals = {
    vue: 'Vue',
    'vue-router': 'VueRouter',
    'element-ui': 'ElementUI'
  }
  config.externals(externals)

  const cdn = {
    css: [
      'https://cdn.bootcdn.net/ajax/libs/element-ui/2.12.0/theme-chalk/index.css'
    ],
    js: [
      'https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.min.js',
      'https://cdn.bootcdn.net/ajax/libs/vue-router/3.1.3/vue-router.min.js',
      'https://cdn.bootcdn.net/ajax/libs/element-ui/2.12.0/index.js'
    ]
  }
  config
    .plugin('html')
    .tap(args => {
      args[0].cdn = cdn
      return args
    })
}
